import { Table } from 'antd';
import { connect } from 'umi';
import { useEffect, useMemo, useState } from 'react';
import { getTableColumns } from '../mconfig/Tablecolumn';
import { Form, Button, DatePicker, Card } from 'antd';
import { ManageService } from '../services';
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import moment from 'moment';
import _ from 'lodash';
import '../common/style.less';
import * as ExcelJs from 'exceljs';
import { saveAs } from "file-saver";
import { Workbook } from "exceljs";
const AssetDeprecitionManageView: React.FC<AssetDeprecitionManageAPI.IManageType> = ({ curRes }) => {
    
    // 详情数据
    const [dataSource, setDataSource] = useState<any>([]);

    const manageServiceCallback = (res) => {
        let data = _.cloneDeep(res?.obj)
        data?.map(item => {
            if (item?.kyList && item?.kyList.length > 0 || item?.znList && item?.znList.length) {
                item.children = (item?.kyList || []).concat(item?.znList || [])
            }
        })
        setDataSource(data)
    }

    /**  获取管理页数据 */
    const { manageServiceReturnRun, manageServiceReturnLoading } = ManageService(manageServiceCallback, curRes);

    /** 搜索表单form */
    const [searchForm] = Form.useForm();

    const getTableColumn: Record<string, any>[] = useMemo(() => {
        return getTableColumns();
    }, [curRes]);
  
    /**  搜索列表 */
    const onSearch = () => {
        const data = searchForm.getFieldsValue()
        let queryData = {
            year: '',
            month: '',
        }
        if (data.date) {
            const date = new Date(data.date)
            queryData.year = date.getFullYear().toString()
            queryData.month = (date.getMonth() + 1).toString()
        } else {
            const today = new Date();
            const date = new Date(today.getFullYear(), today.getMonth() - 1);
            queryData.year = date.getFullYear().toString()
            queryData.month = (date.getMonth() + 1).toString()
        }
        manageServiceReturnRun(queryData);
    };
    
    /** 设置默认日期为上个月 */
    const setDefaultDate = () => {
        const today = new Date();
        const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1);
        return lastMonth
    };

    const onExportMultiHeaderExcel = () => {
        let exportData = [] as any
        dataSource?.map(item => {
            exportData?.push(item)
            if (item?.children && item?.children.length > 0) {
                exportData = exportData.concat(item?.children)
            }
        })
        // 创建工作簿
        const workbook = new ExcelJs.Workbook();
        // 添加sheet
        const worksheet = workbook.addWorksheet('资产折旧分摊');
        // 设置 sheet 的默认行高
        worksheet.properties.defaultRowHeight = 20;
        // 设置列
        worksheet.columns = getTableColumn;
        // 添加行
        worksheet.addRows(exportData);
        // 导出excel
        saveWorkbook(workbook, '资产折旧分摊.xlsx');
    }

    // 保存文件
    const saveWorkbook = (workbook: Workbook, fileName: string) => {
      // 导出文件
      workbook.xlsx.writeBuffer().then((data => {
        const blob = new Blob([data], {type: ''});
        saveAs(blob, fileName);
      }))
    }

    /** 初始化 */
    useEffect(() => {
        const data = searchForm.getFieldsValue()
        let queryData = {
            year: '',
            month: '',
        }
        if (data.date) {
            const date = new Date(data.date)
            queryData.year = date.getFullYear().toString()
            queryData.month = (date.getMonth() + 1).toString()
        } else {
            const today = new Date();
            const date = new Date(today.getFullYear(), today.getMonth() - 1);
            queryData.year = date.getFullYear().toString()
            queryData.month = (date.getMonth() + 1).toString()
        }
        manageServiceReturnRun(queryData);
    }, []);

    return (
        <>
            <div>
                <Card>
                    <div style={{display: 'flex', justifyContent: 'space-between'}}>
                        <Form form={searchForm}>
                            <Form.Item name='date' initialValue={moment(setDefaultDate())} style={{marginBottom: 0}}>
                                <DatePicker
                                    picker='month'
                                    format='YYYY-MM'
                                    placeholder='请选择'
                                    allowClear={false}
                                />
                            </Form.Item>
                        </Form>
                    <Button type={'primary'} icon={<SearchOutlined />} onClick={onSearch}>查询</Button>
                    </div>
                </Card>
                <Card style={{marginTop: '4px', paddingTop: '0'}}>
                    <div style={{paddingBottom: '8px', display: 'flex', justifyContent: 'flex-end'}}>
                        <Button type="primary" icon={<DownloadOutlined />} 
                            onClick={onExportMultiHeaderExcel}>
                            下载
                        </Button>
                    </div>
                    <Table columns={getTableColumn} bordered size="small" dataSource={dataSource} rowKey={(res) => res?.useDepartmentId} scroll={{ x: 1200, y: 600 }} pagination={false} loading={manageServiceReturnLoading}
                     rowClassName={res => ((res.useDepartmentName == '科研部门小计' || res.useDepartmentName == '职能部门小计') ? 'table-color-dust' : '')}
                     />
                </Card>
            </div>
        </>
    );

};

export default connect(({ baseLogin }: Record<string, any>) => ({
    curRes: baseLogin?.permissions,
}))(AssetDeprecitionManageView);